package com.ext.aic.handler;

import com.ext.aic.beans.Pagination;
import com.eyinfo.android_pure_utils.utils.ObjectJudge;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.List;

import lombok.Getter;

public class PageHandler<Item> {

    private int currentPage = 1;
    private int pageSize = 20;
    @Getter
    private List<Item> items = new ArrayList<>();

    protected void onRequestData(int page, int size) {

    }

    public void refresh() {
        onRequestData(currentPage, pageSize);
    }

    public void registerListener(RefreshLayout refreshLayout) {
        refreshLayout.setOnRefreshListener(layout -> {
            currentPage = 1;
            items.clear();
            onRequestData(currentPage, pageSize);
            layout.finishRefresh();
        });
        refreshLayout.setOnLoadMoreListener(layout -> {
            currentPage++;
            onRequestData(currentPage, pageSize);
            layout.finishLoadMore();
        });
    }

    public boolean isEmptyData(List<Item> data, Pagination pagination) {
        return pagination.getPage() == 1 && ObjectJudge.isNullOrEmpty(data);
    }

    public void loadDone(SmartRefreshLayout refreshLayout, Pagination pagination, List<Item> data) {
        int page = pagination.getPage();
        int size = pagination.getPageSize();
        int total = pagination.getTotal();
        if (page == 1) {
            items.clear();
            currentPage = 1;
        }
        if (!ObjectJudge.isNullOrEmpty(data)) {
            items.addAll(data);
        }
        if (page * size >= total) {
            refreshLayout.finishLoadMoreWithNoMoreData();
        }
    }
}
